import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './fenzi.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Popconfirm, Tree } from 'antd';
import { IconC, InfoTipsC } from '../../../comps';
import dictData from './config';
import { getProductName } from '../../../utils/utils';
import { showValue2 } from '../../PortfolioManagement/utils';

const { TreeNode } = Tree;

class CardTreeListC extends PureComponent {
  state = {
    controlValueType: 1, // 控制类别显示的是什么 0:是否下拉，1:树形下拉 ，2:输入框
    components: [], // 公式下面的 关系公式 树形结构
    index: 1, // 树形结构 每新增一个节点 key+1  值给components的父节点和子节点里的 key 和 conditionSeq
    Factor: [], // 计算因子下拉
    conditionBoundList: [], // 证券类型下拉
    conditionOrigin: [], // 证券类型原始数据
    controlValuesList: [], // 控制类别下拉数据
    compareMethodList: [], // 比较方向下拉
    RiskIndexInfo: [],
    currentNode: undefined, // 点击树节点 存储节点的数据
    conditionConfigId: '', // 存放当前根节点id
    value: ['0-0-0'],
    group: 0, // 当前在父节点下建立子节点1  新建的只有父节点0
  };

  str = '';

  componentDidMount() {
    const { data } = this.props;
    this.props.onRef(this);
    this.setState({
      components: data,
    });
  }

  componentDidUpdate(prevProps) {
    if (JSON.stringify(this.props.data) != JSON.stringify(prevProps.data)) {
      this.setState({
        components: this.props.data,
      });
    }
  }

  // 根据groupId 查询当前选中项的 currentNode数据
  queryRecord = (conditionConfigId, data, result) => {
    data.map((item) => {
      if (item.conditionConfigId == conditionConfigId) {
        result.push(item);
      } else if (item.conditionList && item.conditionList.length > 0) {
        this.queryRecord(conditionConfigId, item.conditionList, result);
      }
    });
    return result;
  };

  // 点击树形里每行文字 查到具体数据回填
  clickNode = (conditionConfigId) => {
    const { components, group } = this.state;
    const { conditionOrigin } = this.props;
    const result = [];
    const that = this;
    const currentNode = this.queryRecord(conditionConfigId, components, result)[0];
    // 根据证券范围渲染
    conditionOrigin.map((item) => {
      if (!currentNode) return;
      if (item.boundName == currentNode.conditionBoundName) {
        // 决定比较方向下拉 和 控制类别展示形式
        currentNode.controlValueType = item.controlValueType;
        // currentNode.compareMethodType = item.compareMethod;
      }
    });
    // currentNode回填的数据不存在  则返回，并将group重置为0
    if (currentNode == undefined) {
      this.setState({
        group: 0,
      });
      this.props.getCurrentNode(undefined); // 抛出节点信息
      return;
    }
    if (currentNode.conditionBoundNo == '' && currentNode.compareMethod == '' && currentNode.controlValue == '') {
      this.setState({
        group: 1,
      }); // currentNode回填的数据 控制范围 控制方法为空将group赋值1 否则重置0
    } else {
      this.setState({
        group: 0,
      });
      if (conditionOrigin) {
        const ConditionOne = conditionOrigin.filter((item) => item.boundNo == currentNode.conditionBoundNo);

        if (ConditionOne.length > 0) {
          that.setState({
            controlValuesList: ConditionOne[0].controlValuesList,
          });
        } else {
          that.setState({
            controlValuesList: [],
          });
        }
      }
      if (currentNode.controlValue && typeof currentNode.controlValue === 'string') {
        currentNode.controlValue = currentNode.controlValue.split(' ');
      }
      if (currentNode) {
        if (currentNode.conditionBoundNo == 0) {
          currentNode.conditionBoundNo = '';
        }
      }
    }
    this.props.getCurrentNode(currentNode.controlValue && !currentNode.controlValue.length ? undefined : currentNode); // 抛出节点信息
    this.setState({
      conditionConfigId,
      currentNode,
    });
  };

  // 添加关系 根节点 未选择任何节点时，【添加关系】或者【新建公式】时都是添加到根节点是上；
  addRelation = (params) => {
    const { components, index, conditionConfigId, group, conditionOrigin } = this.state;
    const newData = _.cloneDeep(components);
    const controlValueList = [];
    const that = this;
    controlValueList.push(params.controlValue);
    if (group == 1) {
      // 新增的是子节点
      that.addRisk(newData, conditionConfigId, params, index);
    } else {
      // 新增的是根节点
      newData.push({
        key: index,
        conditionConfigId: new Date().getTime(),
        parentId: '',
        // conditionSeq: index,
        conditionType: 1,
        joinTypeMode: Number(params.joinTypeMode),
        conditionBoundNo: 0,
        compareMethod: 0,
        controlValue: [], // controlValue,
        conditionList: [],
      });
    }

    this.setState({ components: newData, index: index + 1 });
  };

  addRisk = (data, conditionConfigId, params, index) => {
    data.map((item) => {
      if (item.conditionConfigId == conditionConfigId) {
        item.conditionBoundNo = 0;
        item.compareMethod = 0;
        item.controlValue = [];
        item.conditionList.push({
          key: index,
          conditionConfigId: (Date.now && Date.now()) || new Date().getTime(),
          parentId: conditionConfigId,
          // conditionSeq: index,
          conditionType: 1,
          joinTypeMode: Number(params.joinTypeMode),
          conditionBoundNo: 0,
          compareMethod: 0,
          controlValue: [],
          conditionList: [],
        });
      } else if (item.conditionList && item.conditionList.length > 0) {
        this.addRisk(item.conditionList, conditionConfigId, params, index);
      }
    });
  };

  // 格式化公式结构
  create = (data, conditionConfigId, params, conditionBoundName, index) => {
    data.map((item) => {
      if (item.conditionConfigId == conditionConfigId) {
        item.conditionBoundNo = 0;
        item.compareMethod = 0;
        item.controlValue = [];
        item.conditionList.push({
          key: index,
          conditionConfigId: new Date().getTime(),
          parentId: conditionConfigId,
          // conditionSeq: index,
          conditionType: 1,
          joinTypeMode: Number(params.joinTypeMode),
          conditionBoundName,
          conditionBoundNo: Number(params.conditionBoundNo),
          compareMethod: Number(params.compareMethod),
          controlValue: typeof params.controlValue === 'string' ? params.controlValue.split(' ') : params.controlValue,
          controlValueName: params.controlValueName instanceof Array ? JSON.stringify(params.controlValueName) : params.controlValueName,
          conditionList: [],
          indexCategory: params.indexCategory,
        });
      } else if (item.conditionList && item.conditionList.length) {
        this.create(item.conditionList, conditionConfigId, params, conditionBoundName, index);
      }
    });
  };

  // 新建公式 子节点一般  未选择任何节点时，【新建公式】时都是添加到根节点上；
  addExpression = (params) => {
    const { components, index, group, conditionConfigId } = this.state;
    const { conditionOrigin } = this.props;
    const newData = components.map((item) => ({ ...item }));
    const controlValue = [];
    let conditionBoundName = '';
    const that = this;
    controlValue.push(params.controlValue);
    if (params.conditionBoundNo == undefined) {
      params.conditionBoundNo = '';
    }
    if (params.compareMethod == undefined) {
      params.compareMethod = '';
    }
    if (params.conditionBoundNo) {
      conditionOrigin.map((item) => {
        if (item.boundNo == params.conditionBoundNo) {
          // 比对出证券类型名称
          conditionBoundName = item.boundName;
        }
      });
    }
    if (group == 1) {
      // 新增子节点
      that.create(newData, conditionConfigId, params, conditionBoundName, index);
    } else {
      // 根据key值 能表单
      newData.push({
        key: index,
        conditionConfigId: new Date().getTime(),
        parentId: '-1', // 父节点为-1 表示为公式节点 通过点击新建公式得到的根节点
        // conditionSeq: index,
        conditionType: 1,
        joinTypeMode: Number(params.joinTypeMode),
        conditionBoundName,
        conditionBoundNo: Number(params.conditionBoundNo),
        compareMethod: Number(params.compareMethod),
        controlValue: params.controlValue instanceof Array ? params.controlValue : [params.controlValue],
        controlValueName: params.controlValueName instanceof Array ? JSON.stringify(params.controlValueName) : params.controlValueName,
        conditionList: [],
        indexCategory: params.indexCategory,
      });
    }
    this.setState({ components: newData, index: index + 1 });
  };

  // 遍历删除 返回的新数据
  delete = (data, conditionConfigId) => {
    const newData = data.filter((x) => x.conditionConfigId != conditionConfigId);
    newData.map((x) => x.conditionList && (x.conditionList = this.delete(x.conditionList, conditionConfigId)));
    return newData;
  };

  // 删除节点 父子节点 都可以
  deleteComponents = () => {
    const { components, index, conditionConfigId } = this.state;
    const that = this;
    const newcomponents = that.delete(components, conditionConfigId);
    that.setState({
      components: newcomponents,
      group: 0,
      currentNode: undefined, // 删除当前节点数据
    });
    this.props.getCurrentNode(undefined);
  };

  // 遍历x修改 返回的新数据 修改的公式节点
  modify = (data, conditionConfigId, params, conditionBoundName) => {
    data.map((item) => {
      if (item.conditionConfigId == conditionConfigId) {
        item.joinTypeMode = Number(params.joinTypeMode);
        item.conditionBoundName = conditionBoundName;
        item.conditionBoundNo = conditionBoundName == '' ? '' : Number(params.conditionBoundNo);
        item.compareMethod = Number(params.compareMethod);
        item.controlValue = params.controlValue instanceof Array ? params.controlValue : [params.controlValue];
        item.controlValueName = params.controlValueName instanceof Array ? JSON.stringify(params.controlValueName) : params.controlValueName;
      } else if (item.conditionList && item.conditionList.length > 0) {
        this.modify(item.conditionList, conditionConfigId, params, conditionBoundName);
      }
    });
  };

  // 修改公式节点
  editExpression = (params) => {
    const { components, index, conditionConfigId, group } = this.state;
    const { conditionOrigin } = this.props;
    const that = this;
    if (params.compareMethod == undefined) {
      params.compareMethod = '';
    }
    if (group == 0) {
      const newData = components.map((item) => ({ ...item }));
      const controlValue = [];
      controlValue.push(params.controlValue instanceof Array ? params.controlValue : [params.controlValue]);
      // 判断控制范围 对应的boundName
      let conditionBoundName = '';
      if (params.conditionBoundNo) {
        conditionOrigin &&
          conditionOrigin.map((item) => {
            // 根据控制范围的val与控制范围的下拉数组的boundNo比较出数据 找出boundName
            if (item.boundNo == params.conditionBoundNo) {
              conditionBoundName = item.boundName;
            }
          });
      }
      if (conditionBoundName == '' && params.compareMethod == '') {
        that.setState({
          group: 0,
        });
      }
      this.modify(newData, conditionConfigId, params, conditionBoundName);
      this.setState({ components: newData });
    }
  };

  showName2 = (controlValue, controlValueName) => {
    if (controlValueName == undefined || controlValueName == '') return controlValue;
    if (controlValueName.indexOf('[') < 0) {
      return controlValueName;
    }
    return JSON.parse(controlValueName).join('、');
  };

  // 生成树形结构dom
  renderTrees = (data) => {
    return data.map((item) => {
      if (item.conditionList && item.conditionList.length) {
        return (
          <TreeNode title={this.renderNode(item)} key={item.conditionConfigId} dataRef={item}>
            {this.renderTrees(item.conditionList)}
          </TreeNode>
        );
      }
      return <TreeNode title={this.renderNode(item)} key={item.conditionConfigId} />;
    });
  };

  // 得到树形下拉参数treeData
  getTreeData = (data) => {
    const myTree = [];
    data.map((item) => {
      if (item.conditionList && item.conditionList.length) {
        const arr = this.getTreeData(item.conditionList);
        myTree.push({ key: item.conditionConfigId, title: this.renderNode(item), children: arr });
      } else {
        myTree.push({ key: item.conditionConfigId, title: this.renderNode(item) });
      }
    });
    return myTree;
  };

  // 节点展示dom
  renderNode = (item) => {
    const { conditionConfigId } = this.state;
    const {
      limitSetting: { dictMap },
    } = this.props;
    return (
      <div className={myStyle.myNode}>
        <span>{showValue2('sql_join_type', dictMap, item.joinTypeMode.toString())}</span>
        <span style={{ display: item.compareMethod ? 'inline' : 'none' }}>
          【{item.conditionBoundName ? item.conditionBoundName : item.conditionBoundNo != 0 ? item.conditionBoundNo.toString() : ''}】
        </span>
        <span style={{ display: item.compareMethod ? 'inline' : 'none' }}>
          {' '}
          {getProductName(item.compareMethod != 0 ? item.compareMethod.toString() : '', dictData.directionList)}
        </span>
        <div>
          <div style={{ display: item.compareMethod ? 'flex' : 'none' }}>
            【<div title={this.showName2(item.controlValue, item.controlValueName)}>{this.showName2(item.controlValue, item.controlValueName)}</div>】
          </div>
          <span style={{ display: conditionConfigId == item.conditionConfigId ? 'inline' : 'none' }}>
            <Popconfirm
              title={'确定删除？'}
              icon={<ExclamationCircleOutlined />}
              onConfirm={() => {
                this.deleteComponents();
              }}
            >
              <IconC type='delete' isHover={false} />
            </Popconfirm>
          </span>
        </div>
      </div>
    );
  };

  // 点击树节点触发
  onSelect = (selectedKeys, info) => {
    console.log(selectedKeys, '树节点');
    if (selectedKeys && selectedKeys.length) {
      this.clickNode(selectedKeys[0]);
    } else {
      // 未选中任何节点 下次新增的是根节点
      this.setState({
        group: 0,
        conditionConfigId: undefined,
      });

      if (this.state.currentNode) {
        if (this.state.currentNode.parentId == '') this.props.getCurrentNode(undefined);
      }
    }
  };

  // 关系 公式列表展示
  renderCardList = () => {
    const { components } = this.state;
    const treeadata = this.getTreeData(components);
    return (
      <div className={myStyle.cardList}>
        <Tree checkable={false} treeData={treeadata} virtual={true} defaultExpandParent={true} onSelect={this.onSelect} defaultExpandAll={true} />
      </div>
    );
  };

  renderItem = (data) => {
    // 只翻译了三层结构
    this.str = '';
    data &&
      data.map((item, key) => {
        if (item.conditionList && item.conditionList.length) {
          if (key !== 0) this.str += ` ${this.showValue(item.joinTypeMode)} `; // 关系节点 展示|| &&
          let a = '';
          item.conditionList.map((child, index) => {
            if (child.conditionList && child.conditionList.length) {
              a += ` ${this.showValue(child.joinTypeMode)} `; // 关系节点 展示|| &&
              let b = '';
              child.conditionList.map((cc, indexc) => {
                const temp = this.transformName(cc, indexc != 0);
                b += temp;
              });
              a += `(${b})`; // 包裹每个关系节点下的数据
            } else {
              const temp = this.transformName(child, index != 0);
              a += temp;
            }
          });
          this.str += `(${a})`; // 包裹每个关系节点下的数据
        } else {
          this.str += this.transformName(item, key != 0);
        }
      });
    return this.str;
  };

  transformName = (item, type) => {
    const {
      limitSetting: { dictMap },
    } = this.props;
    return `<div class=${myStyle.myNode1}>
               <span  style=display:${type && item.compareMethod ? 'inline' : 'none'}>${this.showValue(item.joinTypeMode)}</span>
                <span  style=display:${item.compareMethod ? 'inline' : 'none'}>【${
      item.conditionBoundName ? item.conditionBoundName : item.conditionBoundNo != 0 ? item.conditionBoundNo.toString() : ''
    }】</span>    
                <span  style=display:${item.compareMethod ? 'inline' : 'none'}> ${getProductName(
      item.compareMethod != 0 ? item.compareMethod.toString() : '',
      dictData.directionList,
    )}</span>   
                <div > 
                    <div style=display:${item.compareMethod ? 'flex' : 'none'}>
                        <div title=${this.showName2(item.controlValue, item.controlValueName)}>【${this.showName2(item.controlValue, item.controlValueName)}】</div>
                    </div>
                </div> 
            </div>`;
  };

  // 展示&& ||
  showValue = (mode) => {
    let str = '';
    dictData.joinTypeMode.map((item) => {
      if (mode == item.value) str = item.fuhao;
    });
    return str;
  };

  // 关系 公式列表展示
  renderBottomList = () => {
    const { components } = this.state;
    const content = this.renderItem(components || []);
    return components?.length ? <div className={myStyle.bottomList} dangerouslySetInnerHTML={{ __html: content }} /> : null;
  };

  render() {
    return (
      <div>
        {this.renderCardList()}
        <div style={{ margin: '8px 0' }}>
          <InfoTipsC Left='建议最多设置3层嵌套的关联规则。' style={{ paddingLeft: '16px', width: '100%' }} />
        </div>
        {this.renderBottomList()}
      </div>
    );
  }
}
export default connect(({ limitSetting, dictionaryM, userM: user, loading }) => ({
  limitSetting,
  dictionaryM,
  user,
  loading,
}))(CardTreeListC);
